package com.reder.practice.service.impl;

import com.reder.practice.bean.extend.FollowerExtend;
import com.reder.practice.bean.extend.UserExtend;
import com.reder.practice.common.dto.ServerResponse;
import com.reder.practice.common.enums.state.FollowState;
import com.reder.practice.common.event.FollowEvent;
import com.reder.practice.common.event.NotFollowEvent;
import com.reder.practice.common.util.SqlResultUtil;
import com.reder.practice.dao.FollowerDao;
import com.reder.practice.dao.UserDao;
import com.reder.practice.service.FollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 关注业务接口实现类
 *
 * @author Fish
 * <p>Email: fishinlove@163.com</p>
 * <p>created by 2019/09/23 19:23:06</p>
 */
@Service
@Slf4j
public class FollowServiceImpl implements FollowService {

    @Resource
    private FollowerDao followerDao = null;

    @Resource
    private UserDao userDao = null;

    @Resource
    private ApplicationContext context = null;

    @Override
    @Transactional
    public ServerResponse follow(long followerId, long userId) {
        context.publishEvent(new FollowEvent(userId, followerId));
        incrementFollowAmount(followerId, userId);
        return SqlResultUtil.checkSqlResult(
                followerDao.insert(FollowerExtend.newFollower(followerId, userId)),
                FollowState.FOLLOW_FAILED
        );
    }

    @Override
    @Transactional
    public ServerResponse notFollow(long followerId, long userId) {
        context.publishEvent(new NotFollowEvent(userId, followerId));
        decrementFollowAmount(followerId, userId);
        return SqlResultUtil.checkSqlResult(
                followerDao.deleteByUserIdAndFollowerId(userId, followerId),
                FollowState.NOT_FOLLOW_FAILED
        );
    }

    // 增加关注数和粉丝数
    @Transactional
    public void incrementFollowAmount(long followerId, long userId) {
        userDao.incrementFollowAmount(followerId);
        userDao.incrementFollowerAmount(userId);
    }

    // 减少关注数和粉丝数
    @Transactional
    public void decrementFollowAmount(long followerId, long userId) {
        userDao.decrementFollowAmount(followerId);
        userDao.decrementFollowerAmount(userId);
    }
}
